import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import static org.lwjgl.opengl.GL11.GL_FALSE;
import static org.lwjgl.opengl.GL20.*;

public abstract class ShaderHelper
{
	public static int createShaderProgram(String baseName)
	{
		int program = glCreateProgram();
		int vertShader = glCreateShader(GL_VERTEX_SHADER);
		int fragShader = glCreateShader(GL_FRAGMENT_SHADER);
		StringBuilder vertBuilder = new StringBuilder(), fragBuilder = new StringBuilder();
		try
		{
			BufferedReader vertexReader = new BufferedReader(new FileReader(baseName + ".vert"));
			String curLine = "";
			while((curLine = vertexReader.readLine()) != null)
			{
				vertBuilder.append(curLine).append("\n");
			}
		}
		catch(IOException e)
		{
			System.err.println("Failed to read vertex shader");
			e.printStackTrace();
			System.exit(1);
		}
		try
		{
			BufferedReader fragmentReader = new BufferedReader(new FileReader(baseName + ".frag"));
			String curLine = "";
			while((curLine = fragmentReader.readLine()) != null)
			{
				fragBuilder.append(curLine).append("\n");
			}
		}
		catch(IOException e)
		{
			System.err.println("Failed to read fragment shader");
			e.printStackTrace();
			System.exit(1);
		}
		glShaderSource(vertShader, vertBuilder.toString());
		glShaderSource(fragShader, fragBuilder.toString());
		glCompileShader(vertShader);
		glCompileShader(fragShader);
		glAttachShader(program, vertShader);
		glAttachShader(program, fragShader);
		glLinkProgram(program);
		glDeleteShader(vertShader);
		glDeleteShader(fragShader);
		
		if(glGetShaderi(vertShader, GL_COMPILE_STATUS) == GL_FALSE) System.err.println("Error compiling vertex shader: \n" + glGetShaderInfoLog(vertShader, 1024));
		if(glGetShaderi(fragShader, GL_COMPILE_STATUS) == GL_FALSE) System.err.println("Error compiling fragment shader: \n" + glGetShaderInfoLog(fragShader, 1024));
		if(glGetProgrami(program, GL_LINK_STATUS) == GL_FALSE) System.err.println("Error linking shaders in program: \n" + glGetProgramInfoLog(program, 1024));
		
		return program;
	}
}